package com.wei.frame.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.IntRange;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.bumptech.glide.Glide;
import com.wei.frame.R;
import com.wei.frame.utils.Preconditions;

import java.util.ArrayList;
import java.util.List;


/**
 * 作者:赵若位
 * 时间:2019/7/31 23:27
 * 功能:基础的ReclerView.Adapter
 */
public abstract class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
    private static final int EMPTY = 0x100;//无数据
    private static final int CONTENT = 0x101;//有数据

    protected Context mContext;
    private List<T> mList;
    private int mEmptyLayoutID;//空布局
    private int mLayoutID;
    private int mViewCacheSize = 20;
    private boolean isEmpty;//是否显示空布局
    protected int mPosition = -1;

    public BaseRecyclerViewAdapter(@Nullable Context context, @LayoutRes int layoutID) {
        this.mContext = Preconditions.checkNotNull(context, "The %s is empty~",
                context.getClass().getSimpleName());
        this.mLayoutID = layoutID;
        this.mEmptyLayoutID = R.layout.layout_adapter_normal_empty;
        mList = new ArrayList<>();
    }


    /*RecyclerView绑定Adapter*/
    public void bindRecyclerView(@Nullable RecyclerView recyclerView) {
        if (recyclerView == null) {
            throw new NullPointerException("The Bind RecyclerView is Empty!");
        }
        /*关闭刷新动效*/
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        recyclerView.setItemViewCacheSize(mViewCacheSize);
        recyclerView.setHasFixedSize(true);
        //列表滚动过程中禁止加载图片卡顿列表
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(mContext).resumeRequests();
                } else {
                    Glide.with(mContext).pauseRequests();
                }
            }
        });
        recyclerView.setAdapter(this);
    }


    public int getPosition() {
        return mPosition;
    }

    public void setPosition(int position) {
        mPosition = position;
        notifyDataSetChanged();
    }

    /*设置空布局ID*/
    public BaseRecyclerViewAdapter setEmpty(@LayoutRes int layoutID) {
        this.mEmptyLayoutID = layoutID;
        notifyDataSetChanged();
        return this;
    }


    /*设置ItemView缓存个数*/
    public BaseRecyclerViewAdapter setViewCacheSize(int cacheSize) {
        this.mViewCacheSize = cacheSize;
        return this;
    }

    public List<T> getData() {
        return mList;
    }

    public T getData(int position) {
        if (null != mList && position < mList.size() && position >= 0) {
            return mList.get(position);
        }
        return null;
    }


    /*更新内容中所有的数据*/
    public void setNewData(@Nullable List<T> list) {
        this.mList = (list == null) ? new ArrayList<T>() : list;
        notifyDataSetChanged();
    }

    /*插入一组数据*/
    public void setData(@Nullable List<T> list, @IntRange(from = 0) int position) {
        if (list != null && list.size() != 0) {
            int index = getInsertPosition(position);
            this.mList.addAll(index, list);
            notifyItemRangeInserted(index, list.size());
        }
    }

    /*插入一组数据*/
    public void setData(@Nullable List<T> list) {
        if (null != list && list.size() != 0) {
            int position = mList.size();
            this.mList.addAll(list);
            if (0 == position) {
                notifyDataSetChanged();
            } else {
                notifyItemRangeInserted(position, list.size());
            }
        }
    }

    /*插入一条数据*/
    public void setData(@Nullable T t, @IntRange(from = 0) int position) {
        if (t != null) {
            int index = getInsertPosition(position);
            this.mList.add(index, t);
            notifyItemRangeInserted(index, 1);
        }
    }

    /*插入一条数据*/
    public void setData(@Nullable T t) {
        this.setData(t, mList.size());
    }


    /*获取数据插入的位置*/
    private int getInsertPosition(@IntRange(from = 0) int position) {
        return (position < 0 || position > mList.size()) ? mList.size() : position;
    }

    /*设置是否显示空布局页面*/
    public BaseRecyclerViewAdapter<T> setIsEmpty(Boolean empty) {
        this.isEmpty = empty;
        return this;
    }

    /*是否显示空数据Layout*/
    protected final boolean isDisplayEmpty() {
        return isEmpty && (mList == null || mList.isEmpty());
    }


    @Override
    public int getItemViewType(int position) {
        if (isDisplayEmpty()) {
            return EMPTY;
        } else {
            return CONTENT;
        }
    }


    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int type) {
        return BaseViewHolder.getViewHolder(LayoutInflater.from(mContext).
                inflate(type == EMPTY ? mEmptyLayoutID : mLayoutID, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {
        if (getItemViewType(position) == CONTENT && mList != null && mList.get(holder.getAdapterPosition()) != null) {
            convert(position, holder, mList.get(holder.getAdapterPosition()));
        }
    }

    @Override
    public int getItemCount() {
        return (isDisplayEmpty()) ? 1 : mList.size();
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager instanceof GridLayoutManager) {
            final GridLayoutManager gridManager = ((GridLayoutManager) manager);
            gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return isDisplayEmpty() ? gridManager.getSpanCount() : 1;
                }
            });
        }
    }

    @Override
    public void onViewAttachedToWindow(@NonNull BaseViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
        if (lp != null
                && lp instanceof StaggeredGridLayoutManager.LayoutParams
                && isDisplayEmpty()) {
            StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
            p.setFullSpan(true);
        }
    }

    protected abstract void convert(int position, @Nullable BaseViewHolder holder, @Nullable T data);
}
